import React, { useState } from 'react';
import {
    Container,
    Box,
    Typography,
    Button,
    Paper,
    Breadcrumbs,
    Link as MuiLink,
    Alert
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ViewInAr as ModelIcon,
    Add as AddIcon
} from '@mui/icons-material';
import { Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';

import { useModelContext } from '../contexts/ModelContext';
import ThreeModelEditor from '../components/ThreeModelEditor';

const GeometryModelCreate = () => {
    const navigate = useNavigate();
    const { createGeometryModel, error: contextError } = useModelContext();
    const [error, setError] = useState(null);
    const [modelName, setModelName] = useState('');
    const [modelDescription, setModelDescription] = useState('');

    // 处理提交
    const handleSubmit = async (formData) => {
        try {
            setError(null);
            const response = await createGeometryModel(formData);
            if (response) {
                navigate('/models');
            }
        } catch (err) {
            console.error('创建几何体模型失败:', err);
            setError(err.message || '创建几何体模型失败，请稍后再试');
        }
    };

    // 处理取消
    const handleCancel = () => {
        navigate('/models');
    };

    // 从THREE模型编辑器保存
    const handleSaveFromEditor = (modelData) => {
        // 如果有模型名称，使用它，否则使用编辑器提供的名称
        if (modelName) {
            modelData.name = modelName;
        }

        // 如果有模型描述，使用它，否则使用编辑器提供的描述
        if (modelDescription) {
            modelData.description = modelDescription;
        }

        handleSubmit(modelData);
    };

    // 处理模型名称变更
    const handleNameChange = (event) => {
        setModelName(event.target.value);
    };

    // 处理模型描述变更
    const handleDescriptionChange = (event) => {
        setModelDescription(event.target.value);
    };

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Box sx={{ mb: 4 }}>
                <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 2 }}>
                    <MuiLink
                        component={Link}
                        to="/"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        首页
                    </MuiLink>
                    <MuiLink
                        component={Link}
                        to="/models"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型列表
                    </MuiLink>
                    <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                        <AddIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        创建几何体模型
                    </Typography>
                </Breadcrumbs>

                <Paper
                    component={motion.div}
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    elevation={0}
                    sx={{
                        p: 3,
                        backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                        borderRadius: 4,
                        mb: 4,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <Box>
                        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                            创建几何体模型
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            使用3D建模工具创建一个新的几何体模型
                        </Typography>
                    </Box>
                    <Button
                        variant="contained"
                        startIcon={<ArrowBackIcon />}
                        onClick={handleCancel}
                        component={motion.button}
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                    >
                        返回列表
                    </Button>
                </Paper>
            </Box>

            {(error || contextError) && (
                <Alert severity="error" sx={{ mb: 3 }}>
                    {error || contextError}
                </Alert>
            )}

            {/* 模型基本信息 */}
            <Paper sx={{ p: 3, borderRadius: 2, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                    基本信息
                </Typography>
                <Box component="form" sx={{ mt: 2 }}>
                    <Box sx={{ mb: 3 }}>
                        <Typography variant="subtitle2" gutterBottom>
                            模型名称
                        </Typography>
                        <input
                            type="text"
                            value={modelName}
                            onChange={handleNameChange}
                            placeholder="输入模型名称"
                            className="w-full p-2 border border-gray-300 rounded"
                            style={{
                                width: '100%',
                                padding: '8px',
                                border: '1px solid #ccc',
                                borderRadius: '4px'
                            }}
                        />
                    </Box>
                    <Box>
                        <Typography variant="subtitle2" gutterBottom>
                            模型描述
                        </Typography>
                        <textarea
                            value={modelDescription}
                            onChange={handleDescriptionChange}
                            placeholder="输入模型描述（可选）"
                            rows={3}
                            className="w-full p-2 border border-gray-300 rounded"
                            style={{
                                width: '100%',
                                padding: '8px',
                                border: '1px solid #ccc',
                                borderRadius: '4px'
                            }}
                        />
                    </Box>
                </Box>
            </Paper>

            {/* THREE.js 建模编辑器 */}
            <ThreeModelEditor
                onSave={handleSaveFromEditor}
                modelName={modelName}
                modelDescription={modelDescription}
            />
        </Container>
    );
};

export default GeometryModelCreate; 